package yanyan.com.tochar;

import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import com.hjq.permissions.Permission;

import java.io.File;

import yanyan.com.tochar.db.MyMediaRecorder;
import yanyan.com.tochar.db.SoundDiscView;
import yanyan.com.tochar.db.World;
import yanyan.com.tochar.utils.CoreUtil;
import yanyan.com.tochar.utils.FileUtil;
import yanyan.com.tochar.utils.PermissionsUtil;

/**
 * 噪音检测
 */
public class FunsDbActivity extends Activity {
    float volume = 10000;
    private SoundDiscView soundDiscView;
    private MyMediaRecorder mRecorder;
    private static final int msgWhat = 0x1001;
    private static final int refreshTime = 100;
    private TextView dbText,dbMax,dbAvg;
    private int nuumber;//次数
    private int total;//总和
    private int max;//最大

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_funs_db);
        dbText=findViewById(R.id.db_text);
        dbMax=findViewById(R.id.db_max);
        dbAvg=findViewById(R.id.db_avg);
        mRecorder = new MyMediaRecorder();
        PermissionsUtil.authorization(new String[]{Permission.RECORD_AUDIO},this);

       //统计各功能
        CoreUtil.statisticalFuns(this,"funs_db_test");
    }


    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (this.hasMessages(msgWhat)) {
                return;
            }
            volume = mRecorder.getMaxAmplitude();  //获取声压值
            if(volume > 0 && volume < 1000000) {
                World.setDbCount(20 * (float)(Math.log10(volume)));  //将声压值转为分贝值
                soundDiscView.refresh();
                String tips="";
              float fb=  20 * (float)(Math.log10(volume));
                if(fb<20){
                   tips="极度安静";
                }else if(fb>=20 && fb<40){
                   tips="相当于轻声说话";
                }else if(fb>=40 && fb<60){
                    tips="相当于室内谈话";
                }else if(fb>=60 && fb<70){
                    tips="长时间在此环境有损神经";
                }else if(fb>=70 && fb<90){
                    tips="很吵,会使人的神经细胞逐渐受到破坏";
                }else if(fb>=90 && fb<100){
                    tips="会使听力受损";
                }else if(fb>=100){
                    tips="使人难以忍受，几分钟就可暂时致聋";
                }
                dbText.setText(tips);

                //计算平均
                total+=(int)fb;
                nuumber++;
                dbAvg.setText("平均值:"+(total/nuumber));
                //计算最大
                if(fb>max){
                    max=(int)fb;
                }
                dbMax.setText("最大值:"+max);


            }
            handler.sendEmptyMessageDelayed(msgWhat, refreshTime);
        }
    };

    private void startListenAudio() {
        handler.sendEmptyMessageDelayed(msgWhat, refreshTime);
    }

    /**
     * 开始记录
     * @param fFile
     */
    public void startRecord(File fFile){
        try{
            mRecorder.setMyRecAudioFile(fFile);
            if (mRecorder.startRecorder()) {
                startListenAudio();
            }else{
                Toast.makeText(this, "启动录音失败", Toast.LENGTH_SHORT).show();
            }
        }catch(Exception e){
            Toast.makeText(this, "录音机已被占用或录音权限被禁止", Toast.LENGTH_SHORT).show();
            e.printStackTrace();
        }
    }


    @Override
    protected void onResume() {
        super.onResume();
        soundDiscView = (SoundDiscView) findViewById(R.id.soundDiscView);
        File file = FileUtil.createFile("temp.amr");
        if (file != null) {
            Log.v("file", "file =" + file.getAbsolutePath());
            startRecord(file);
        } else {
            Toast.makeText(getApplicationContext(), "创建文件失败", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 停止记录
     */
    @Override
    protected void onPause() {
        super.onPause();
        mRecorder.delete(); //停止记录并删除录音文件
        handler.removeMessages(msgWhat);
    }

    @Override
    protected void onDestroy() {
        handler.removeMessages(msgWhat);
        mRecorder.delete();
        super.onDestroy();
    }
}
